#coding:utf-8
'''
create on 2017-04-20
@author:sandy
'''


from pycommon import TBaseProtocol
import GateFactory
import logging
import GateParse
import GateManager
import CenterBuild

GATE_STATE_INIT               = 0
GATE_STATE_LOGINED            = 1
GATE_STATE_TO_CLOSE           = 2

class GateSrv(TBaseProtocol.TBaseProtocol):

    def __init__(self, pid, addr):
        TBaseProtocol.TBaseProtocol.__init__(self)
        self.__id = pid
        self.__addr = addr
        self.__ip = addr.host.decode('utf-8')
        self.__sid = 0
        self.state = GATE_STATE_INIT 
        
    def getId(self):
        return self.__id
    
    def getSId(self):
        return self.__sid
    
    def getIp(self):
        return self.__ip

    def getState(self):
        return self.state
    
    def packetReceived(self, cmd, pkt):
        if self.state == GATE_STATE_TO_CLOSE:
            return
        try:
            GateParse.parse(self, cmd, pkt)
        except Exception:
            logging.exception(u"Gateparse.parse(), cmd=%d" % cmd)
        
    def sendPacket(self, pkt):
        if not self.isConnected():
            logging.warn(u"sendPacket() not connected")
            return
        TBaseProtocol.TBaseProtocol.sendPacket(self, pkt)
    
    def connectionMade(self):
        logging.debug(u"GateSrv.connectionMade() ip=%s", self.__ip) 
        TBaseProtocol.TBaseProtocol.reset(self)
   
    def connectionLost(self, reason):
        logging.debug(u"GateSrv.connectionLost %s", reason)
        self.state = GATE_STATE_TO_CLOSE
        sid = self.getSId()
        if sid > 0:
            count = GateFactory.instance.getGateSrvCountBySid(sid)
            if count == 1:
                GateManager.instance.gateLogout(sid)
            else:
                logging.warn(u"sid=%d Gate 存在不正常退出情况!",sid)
        logging.debug(u"GateFactory.instance.removeProtocol")
        GateFactory.instance.removeProtocol(self)
        
    def onLogin(self, sid):
        self.__sid = sid 
        self.state = GATE_STATE_LOGINED    

    def kick(self):
        self.__sid = 0
        self.abort() 

    def transPkt2Client(self,uid,pkt):
        self.sendPacket(CenterBuild.transPkt2Client(uid,pkt))

if __name__ == "__main__":
    pass